//
//  XMLPeopleParser.m
//  BVCMS Search
//
//  Created by Allen Thomas on 9/21/10.
//

#import "GenericXMLParser.h"

@implementation GenericXMLParser

@synthesize delegate, currentElement, currentAttributes;    

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	
	if( currentTextString )
    {
        [currentTextString release];
        currentTextString = nil;
    }
	
    self.currentElement = elementName;
    self.currentAttributes = attributeDict;
    
    SEL sel = NSSelectorFromString( [NSString stringWithFormat:@"handleElement_%@:", elementName] );
    if( [delegate respondsToSelector:sel] )
    {
        [delegate performSelector:sel withObject: attributeDict];
    }
	
}

-(void) closeElementWithText
{
    NSString* text = [currentTextString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	
    if( text && self.currentElement )
    {
        SEL sel = NSSelectorFromString( [NSString stringWithFormat:@"handleElementEnd_%@:withText:", currentElement] );
        if( [delegate respondsToSelector:sel] )
        {
            [delegate performSelector:sel withObject: self.currentAttributes withObject: text];
            [currentTextString release];
            currentTextString = nil;
        }
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
	
	if( string && [string length] > 0 )
    {
        if( !currentTextString )
        {
            currentTextString = [[NSMutableString alloc] initWithCapacity:50];
        }
        [currentTextString appendString:string];
    }
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	[self closeElementWithText];
    self.currentElement = nil;
	self.currentAttributes = nil;
	
    SEL sel = NSSelectorFromString( [NSString stringWithFormat:@"handleElementEnd_%@", elementName] );
    if( [delegate respondsToSelector:sel] )
    {
        [delegate performSelector:sel];
    }
	
}

- (void) dealloc {
	
	[delegate release];
	[currentElement release];
	[currentAttributes release];
	[super dealloc];
}



@end
